<template>
  <div class="app-container">
    <aside>将图片进行压缩处理</aside>
    <div style="padding: 8px 24px">
      <el-row :gutter="12">
        <el-col :span="11">
          <div
            style="
              width: 100%;
              height: 72vh;
              border: 1px solid #666;
              border-radius: 5px;
            "
          >
            <div class="uploadImage">
              <uploadFile
                :action="'/api/api/uploadImages'"
                @success="handleAvatarSuccess"
              />
              <!-- <img v-if="imageUrl" :src="imageUrl" />
              <el-button v-else type="primary">点击上传图片</el-button> -->
            </div>
            <!-- <el-upload
              class="avatar-uploader"
              action="/api/api/uploadImages"
              :show-file-list="false"
              :headers="req_headers"
              :on-success="handleAvatarSuccess"
            >
              <div class="uploadImage">
                <img v-if="imageUrl" :src="imageUrl" />
                <el-button v-else type="primary">点击上传图片</el-button>
              </div>
            </el-upload> -->
          </div>

          <div style="height: 10px" />
          <el-tag type="success">大小：{{ imageUrl.length || "0" }}</el-tag>
        </el-col>
        <el-col :span="2">
          <div class="centerButton">
            <el-button type="primary"
              ><i class="el-icon-arrow-left"
            /></el-button>
            <br />
            <el-button type="primary"
              ><i class="el-icon-arrow-right"
            /></el-button>
          </div>
        </el-col>
        <el-col :span="11">
          <div
            style="
              width: 100%;
              height: 72vh;
              border: 1px solid #666;
              border-radius: 5px;
            "
          >
            <div class="uploadImage" @click="Copy">
              <img :src="newImageUrl" />
            </div>
          </div>
          <div style="height: 10px" />
          <el-tag type="success">大小：{{ imageUrl.length || "0" }}</el-tag>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import uploadFile from "@/components/uploadFile.vue";

export default {
  components: {
    uploadFile,
  },
  data() {
    return {
      imageUrl: "",
      newImageUrl: "",
      req_headers: {
        token: JSON.parse(sessionStorage.getItem("userInfo")).token,
      },
    };
  },

  methods: {
    // 图片上传成功
    handleAvatarSuccess(e) {
      const { res } = e;
      this.imageUrl = res.data || "";
      this.compressImg(this.imageUrl, (res) => {
        console.log(res, "res");
        this.newImageUrl = res;
      });
    },

    // 复制压缩后的图片
    async Copy() {
      try {
        await navigator.clipboard.writeText(JSON.stringify(this.newImageUrl));
        this.$message.success("复制成功");
      } catch (error) {
        this.$message.error("复制失败");
      }
    },
    // 图片压缩方法
    compressImg(base64, useImg, multiple = 0.1) {
      // 第一个参数就是需要加密的base65，
      // 第二个是压缩系数 0-1，
      // 第三个压缩后的回调 用来获取处理后的 base64
      if (!base64) {
        return;
      }
      // const _this = this
      const length = base64.length / 1024;
      // 压缩方法
      const newImage = new Image();
      let quality = multiple; // 压缩系数0-1之间
      newImage.src = base64;
      newImage.setAttribute("crossOrigin", "Anonymous"); // url为外域时需要
      let imgWidth, imgHeight;
      let w;
      newImage.onload = function () {
        //  this 指向 newImage
        // 通过改变图片宽高来实现压缩
        w = this.width * multiple;
        imgWidth = this.width;
        imgHeight = this.height;
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
          if (imgWidth > imgHeight) {
            canvas.width = w;
            // 等比例缩小
            canvas.height = w * (imgHeight / imgWidth);
          } else {
            canvas.height = w;
            // 等比例缩小
            canvas.width = w * (imgWidth / imgHeight);
          }
        } else {
          canvas.width = imgWidth;
          canvas.height = imgHeight;

          quality = 0.6;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(this, 0, 0, canvas.width, canvas.height); //  //  this 指向 newImage
        const smallBase64 = canvas.toDataURL("image/*", quality); // 压缩

        // 必须通过回调函数返回，否则无法及时拿到该值，回调函数异步执行
        useImg(smallBase64);
      };
    },
  },
};
</script>

<style scoped>
.centerButton {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  width: 100%;
  height: 78vh;
}

.textarea {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  outline: none;
  color: #666;
  font-size: 12px;
  border: none;
  overflow-y: scroll;
  white-space: break-all;
}

.uploadImage {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  overflow: hidden;
}

.uploadImage .icon {
  font-size: 8rem;
  font-weight: 400;
}

.uploadImage img {
  width: 100%;
}

>>> .avatar-uploader {
  width: 100% !important;
  height: 100% !important;
}

>>> .el-upload,
>>> .el-upload--text {
  width: 100% !important;
  height: 100% !important;
}
</style>
